import configparser


# 可读取配置文件并输出对应的读取代码，复制黏贴到主程序即可

def generate_python_code(section_name_use, configuration_Name):
    return f"{configuration_Name} = {section_name_use}.getint('{configuration_Name}')"


# 创建ConfigParser对象
config = configparser.RawConfigParser()
config.optionxform = lambda option: option  # 确保在使用选项名时保持大小写不变

# 读取配置文件
config.read('relay_configuration(Not_Fully_automatic).ini', encoding='utf-8')

# print("import configparser")
print("# 创建ConfigParser对象")
print("config = configparser.ConfigParser()")
print("# 读取配置文件")
print("config.read('relay_configuration(Not_Fully_automatic).ini', encoding='utf-8')")

# 遍历所有部分并生成对应的Python代码
for section_name in config.sections():
    items = config.items(section_name)
    # print("global ", end="")
    # for Configuration_Name, value in items:
    #     if value.isdigit():  # 判断值是否为数字
    #         print(Configuration_Name, ",", end="")
    print("")
    print(f"{section_name} = config['{section_name}']")
    for Configuration_Name, value in items:
        if value.isdigit():  # 判断值是否为数字
            python_code = generate_python_code(section_name, Configuration_Name)
            print(python_code)


# 第二种方法

def read_config(file_path):
    # 创建ConfigParser对象
    config = configparser.RawConfigParser()
    config.optionxform = lambda option: option  # 确保在使用选项名时保持大小写不变

    # 读取配置文件时使用utf-8编码
    with open(file_path, 'r', encoding='utf-8') as config_file:
        config.read_file(config_file)

    # 初始化字典
    config_dict = {}

    # 遍历配置文件的各个section和key，将其添加到字典中
    for section in config.sections():
        config_dict[section] = {}
        for option in config.options(section):
            config_dict[section][option] = config.get(section, option)

    return config_dict


# 读取配置文件并将配置信息存储到字典中
config_file_path = 'relay_configuration(Not_Fully_automatic).ini'
config_data = read_config(config_file_path)

# 打印字典内容
print(config_data)

# 通过字典读取配置信息
Relay_board_1_Not_Fully_automatic = config_data['Relay_board_1_Not_Fully_automatic']
print(Relay_board_1_Not_Fully_automatic['A_Measuring_valve'])  # 选取配置项中某个配置
print(f"Value for Section1/key1: {Relay_board_1_Not_Fully_automatic}")
